<template>
    <a-card style="margin-bottom: 15px" size="small">
        <template #title>
            <div style="margin: 10px 0px 20px 0px;font-size:16px;">项目结项修改</div>
        </template>
        <template #extra>
            <a-tooltip title="返回上级">
                <a-button size="middle" @click="goback">
                    <template #icon>
                        <RollbackOutlined />
                    </template>
                </a-button>
            </a-tooltip>
        </template>
        <a-steps :current="current" :items="items" type="navigation" @change="StepsChange"></a-steps>
        <div class="steps-content">
            <a-form ref="formRef" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol"
                :labelWrap="true">
                <div v-show="steps[current].title == '第一步'">
                    <a-form-item label="项目编号" name="blprojectnum">
                        <a-select v-model:value="formData.blprojectnum" :allowClear="true" size="Middle"
                            style="width: 100%" @change="onChangePro" :options="options" placeholder="请选择项目"></a-select>
                    </a-form-item>
                    <a-form-item label="项目名称" name="blprojectname">
                        <a-input :disabled="true" style="width: 100%" v-model:value="formData.blprojectname"
                            placeholder="项目名称">
                        </a-input>
                    </a-form-item>
                    <a-form-item label="项目负责人" name="blprojectmanagepeople">
                        <a-select v-model:value="formData.blprojectmanagepeople" :allowClear="true" size="Middle"
                            style="width: 100%" @change="onChangeLeader" :options="optionsLeader"
                            placeholder="请选择项目负责人"></a-select>
                    </a-form-item>
                    <a-form-item label="部门" name="bldept">
                        <a-select v-model:value="formData.bldept" :allowClear="true" size="Middle" style="width:100%"
                            @change="onChangeDept" :options="optionsDept" placeholder="请选择部门"></a-select>
                    </a-form-item>
                    <a-form-item label="项目执行期限" name="Time">
                        <a-range-picker v-model:value="formData.Time" style="width:100%" format="YYYY-MM-DD"
                            @change="onChangeRangeDate" />
                    </a-form-item>
                </div>
                <div v-show="steps[current].title == '第二步'">
                    <div style="margin-bottom:20px;">
                        一、项目执行情况介绍（1000字左右，包括项目介绍、分阶段目标完成情况、资金使用情况等）
                    </div>
                    <a-form-item label="" name="blperforming" :wrapper-col="{ span: 30, offset: 0 }">
                        <a-textarea v-model:value.trim="formData.blperforming" :rows="20" placeholder="请填写" />
                    </a-form-item>
                </div>
                <div v-show="steps[current].title == '第三步'">
                    <div style="margin-bottom:20px;">
                        二、达到的效果及取得的成效
                    </div>
                    <a-form-item label="" name="bleffect" :wrapper-col="{ span: 30, offset: 0 }">
                        <a-textarea v-model:value.trim="formData.bleffect" :rows="20" placeholder="请填写" />
                    </a-form-item>
                </div>
                <div v-show="steps[current].title == '第四步'">
                    <div style="margin-bottom:20px;">
                        三、项目经费决算表
                    </div>
                    <a-table :columns="columns" :data-source="peoplePay" :pagination="false" size="middle">
                        <template #title>
                            <div style="color: #1677ff;font-weight: 600;">
                                人员支出
                            </div>
                        </template>
                        <template v-for="col in columns" :key="item" #bodyCell="{ column, text, record, index }">
                            <div :key="col">
                                <template v-if="column.dataIndex === 'serial'">
                                    {{ index + 1 }}
                                </template>
                                <template v-if="column.dataIndex === 'bldataname'">
                                    <span>{{record.bldataname}}</span>
                                </template>
                                <template v-if="column.dataIndex === 'blmoney'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="peoplePay[index].blmoney" />
                                </template>
                                <template v-if="column.dataIndex === 'bldollar'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="peoplePay[index].bldollar" />
                                </template>
                                <template v-if="column.dataIndex === 'blremarks'">
                                    <a-textarea style="max-height: 32px;margin: -5px 0"
                                        v-model:value.trim="peoplePay[index].blremarks" :rows="2" placeholder="请输入备注" />
                                </template>
                            </div>
                        </template>
                    </a-table>
                    <a-table :columns="columns" :data-source="publicPay" :showHeader="false" :pagination="false"
                        size="middle">
                        <template #title>
                            <div style="color: #1677ff;font-weight: 600;">
                                公用支出
                            </div>
                        </template>
                        <template v-for="col in columns" :key="item" #bodyCell="{ column, text, record,index }">
                            <div :key="col">
                                <template v-if="column.dataIndex === 'serial'">
                                    {{ index + 1 }}
                                </template>
                                <template v-if="column.dataIndex === 'bldataname'">
                                    <span>{{record.bldataname}}</span>
                                </template>
                                <template v-if="column.dataIndex === 'blmoney'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="publicPay[index].blmoney" />
                                </template>
                                <template v-if="column.dataIndex === 'bldollar'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="publicPay[index].bldollar" />
                                </template>
                                <template v-if="column.dataIndex === 'blremarks'">
                                    <a-textarea style="max-height: 32px;margin: -5px 0"
                                        v-model:value.trim="publicPay[index].blremarks" :rows="2" placeholder="请输入备注" />
                                </template>
                            </div>
                        </template>
                    </a-table>
                    <a-table :columns="columns" :data-source="buildPay" :showHeader="false" :pagination="false"
                        size="middle">
                        <template #title>
                            <div style="color: #1677ff;font-weight: 600;">
                                基建支出
                            </div>
                        </template>
                        <template v-for="col in columns" :key="item" #bodyCell="{ column, text, record,index }">
                            <div :key="col">
                                <template v-if="column.dataIndex === 'serial'">
                                    {{ index + 1 }}
                                </template>
                                <template v-if="column.dataIndex === 'bldataname'">
                                    <span>{{record.bldataname}}</span>
                                </template>
                                <template v-if="column.dataIndex === 'blmoney'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="buildPay[index].blmoney" />
                                </template>
                                <template v-if="column.dataIndex === 'bldollar'">
                                    <a-input-number :step="0.01"
                                        :parser="value =>value.match(/^[0-9]*\.([0-9]{0,2})|^[0-9]*/)[0]" string-mode
                                        placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="buildPay[index].bldollar" />
                                </template>
                                <template v-if="column.dataIndex === 'blremarks'">
                                    <a-textarea style="max-height: 32px;margin: -5px 0"
                                        v-model:value.trim="buildPay[index].blremarks" :rows="2" placeholder="请输入备注" />
                                </template>
                            </div>
                        </template>
                    </a-table>
                    <a-table :columns="columns" :data-source="otherPay" :showHeader="false" :pagination="false"
                        size="middle">
                        <template #title>
                            <div style="color: #1677ff;font-weight: 600;">
                                其他资本性支出
                            </div>
                        </template>
                        <template v-for="col in columns" :key="item" #bodyCell="{ column, text, record,index }">
                            <div :key="col">
                                <template v-if="column.dataIndex === 'serial'">
                                    {{ index + 1 }}
                                </template>
                                <template v-if="column.dataIndex === 'bldataname'">
                                    <span>{{record.bldataname}}</span>
                                </template>
                                <template v-if="column.dataIndex === 'blmoney'">
                                    <a-input-number placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="otherPay[index].blmoney" />
                                </template>
                                <template v-if="column.dataIndex === 'bldollar'">
                                    <a-input-number placeholder="例:10.00" style="margin: -5px 0;width: 100%;"
                                        v-model:value="otherPay[index].bldollar" />
                                </template>
                                <template v-if="column.dataIndex === 'blremarks'">
                                    <a-textarea style="max-height: 32px;margin: -5px 0"
                                        v-model:value.trim="otherPay[index].blremarks" :rows="2" placeholder="请输入备注" />
                                </template>
                            </div>
                        </template>
                    </a-table>

                </div>
                <div v-show="steps[current].title == '第五步'">
                    <a-form-item label="请选择项目是否提交审核" name="blstate">
                        <a-select v-model:value="formData.blstate" :allowClear="true" size="Middle" style="width: 100%"
                            placeholder="请选择项目是否提交审核">
                            <!-- <a-select-option :value="6">暂存</a-select-option>
                            <a-select-option :value="1">提交审核</a-select-option> -->
                            <a-select-option :value="6">暂存</a-select-option>
                            <a-select-option :value="0">提交审核</a-select-option>
                        </a-select>

                    </a-form-item>
                    <div>
                        <a-form-item label="当前状态" name="status">
                            <span v-if="formData.status == 5">审核不通过</span>
                            <span v-if="formData.status == 6">暂存</span>
                        </a-form-item>

                    </div>
                </div>
            </a-form>
        </div>
        <div class="steps-action">
            <a-space>
                <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
                    <ArrowLeftOutlined />上一步
                </a-button>
                <a-button v-if="current == steps.length - 1" type="primary" v-throttle @click="onSubmit"> 提交 </a-button>
                <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步
                    <ArrowRightOutlined />
                </a-button>
            </a-space>
        </div>
    </a-card>

</template>

<script setup>
    import { nextTick, reactive, ref, defineProps, onMounted, toRefs, toRaw, computed } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { smartSentry } from '/@/lib/smart-sentry';
    import { ProManageApi } from '/@/api/ProManage/ProManage-api';
    import { ProLeaderApi } from '/src/api/basicManage/DonationManage/ProLeader-api';
    import { employeeApi } from '/src/api/system/employee-api';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { useUserStore } from '/@/store/modules/system/user';
    import dayjs from 'dayjs';
    const emits = defineEmits(['emitPass'])
    const goback = () => {
        let obj = {
            type: 0,
        };
        emits('emitPass', obj);
    };
    //获取信息
    const props = defineProps({
        passData: Object,
    });

    const columns = ref([
        {
            title: '序号',
            dataIndex: 'serial',
            width: '10%',
            align: 'center',
            scopedSlots: { customRender: 'serial' }
        },
        {
            title: '支出内容',
            dataIndex: 'bldataname',
            width: '15%',
            align: 'center',
        },
        {
            title: '预算',
            dataIndex: 'blmoney',
            width: '20%',
            align: 'center',
        },
        {
            title: '实际支出',
            dataIndex: 'bldollar',
            align: 'center',
            width: '20%',
        },
        {
            title: '备注',
            dataIndex: 'blremarks',
            align: 'center',
            width: '35%',
        },
    ])

    const count = computed(() => dataSource.value.length + 1);
    const editableData = reactive({});
    const edit = key => {
        // editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.key)[0]);
    };
    const save = key => {
        Object.assign(dataSource.value.filter(item => key === item.key)[0], editableData[key]);
        delete editableData[key];
    };
    const onDelete = key => {
        dataSource.value = dataSource.value.filter(item => item.key !== key);
    };
    const handleAdd = () => {
        const newData = {
            key: `${count.value}`,
            name: `Edward King ${count.value}`,
            age: 32,
            address: `London, Park Lane no. ${count.value}`,
        };
        dataSource.value.push(newData);
    };
    // 关闭
    function onClose() {
        goback()
    }
    //  步骤条
    const current = ref(0);
    //点击步骤条的事件
    function StepsChange(e) {
        current.value = e;
    }
    //前进
    const next = () => {
        current.value++;
    };
    //后退
    const prev = () => {
        current.value--;
    };
    //步骤条标题
    const steps = [
        {
            title: '第一步',
        },
        {
            title: '第二步',
        },
        {
            title: '第三步',
        },
        {
            title: '第四步',
        },
        {
            title: '第五步',
        },
    ];
    const items = steps.map((item) => ({
        key: item.title,
        title: item.title,
    }));
    // 获取日期
    function onChangeRangeDate(value, dateString) {
        formData.blprojectdatestart = dateString[0];
        formData.blprojectdateend = dateString[1];
    }
    // 项目负责人选择
    const optionsLeader = ref([])
    const onChangeLeader = (value, v) => {
        formData.blprojectmanagepeople = v.label
    }
    // 部门 optionsDept
    const optionsDept = ref([])
    const onChangeDept = (value, v) => {
        formData.bldept = v.label
    }
    // 项目联系人  项目负责人
    async function ajaxQueryContact() {
        try {
            let departList = await ProLeaderApi.foundationNpList();
            const dataSource = departList.data
            optionsLeader.value = dataSource.map(item => ({
                value: item.blleaderlistid,
                label: item.blleadername
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // departList  部门列表
    async function ajaxQuery() {
        try {
            let departList = await employeeApi.departList();
            const dataSource = departList.data
            optionsDept.value = dataSource.map(item => ({
                value: item.bldeptnum,
                label: item.blname
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
        }
    }
    //表单验证规则
    const formRef = ref();
    const labelCol = {
        span: 5,
    };
    const wrapperCol = {
        span: 15,
    };
    const formData = reactive({});
    const rules = {
        blprojectnum: [
            {
                required: true,
                message: '请选择项目',
                trigger: 'change',
            },
        ],
        blprojectmanagepeople: [
            {
                required: true,
                message: '请选择项目负责人',
                trigger: 'change',
            },
        ],
        bldept: [
            {
                required: true,
                message: '请选择部门',
                trigger: 'change',
            },
        ],
        Time: [
            {
                required: true,
                message: '请选择项目执行期限',
                trigger: 'change',
            },
        ],
        blperforming: [
            {
                required: true,
                message: '请输入项目执行情况',
                trigger: 'blur',
            },
        ],
        bleffect: [
            {
                required: true,
                message: '请输入项目达到的效果及取得的成效',
                trigger: 'blur',
            },
        ],
        blstate: [
            {
                required: true,
                message: '请选择提交状态',
                trigger: 'change',
            },
        ],
    }
    // 所属项目
    const options = ref([])
    const proId = ref('')
    // 所属项目  onChangePro
    const onChangePro = (value, v) => {
        formData.blprojectnum = value
        formData.blext2 = value
        proId.value = ProList.value.find(obj => obj.blext2 === value).blprojectnum;
        let result = ProList.value.find(obj => obj.blext2 === value);
        formData.blprojectname = result.blapplyprojectname
    }
    const blsysuserid = ref('');
    blsysuserid.value = computed(() => useUserStore().blsysuserid);
    // 预算提交
    function onSubmit() {
        formRef.value
            .validate()
            .then(async () => {
                SmartLoading.show();
                try {
                    // 将数组合并为一个数组
                    const combinedData = [...peoplePay.value, ...publicPay.value, ...buildPay.value, ...otherPay.value];
                    // 提取只有 ['blmoney', 'bldollar', 'blremarks'] 属性的对象
                    function filterAndAddProperties(arr, props) {
                        const filteredArray = arr.filter(item => {
                            return props.every(prop => item.hasOwnProperty(prop));
                        });
                        const newArray = filteredArray.map(item => {
                            const newItem = {};
                            props.forEach(prop => {
                                newItem[prop] = item[prop];
                            });
                            return newItem;
                        });
                        return newArray;
                    }
                    const filteredAndAddedArray = filterAndAddProperties(combinedData, ['blclosurerecordid', 'bldatanum', 'bldataname', 'blmoney', 'bldollar', 'blremarks']);
                    const newArr = filteredAndAddedArray.map(obj => {
                        // const { bldataname: blext2, bldatanum: blbudgetname, ...rest } = obj; // 解构赋值，将原属性名赋值给新变量
                        const { bldatanum: blbudgetname, bldataname: blext2, blbudgetdataid: blbudgetid, ...rest } = obj; // 解构赋值，将原属性名赋值给新变量
                        return { blbudgetname, blext2, blbudgetid, blclosurerecordid: props.passData.blclosureid, ...rest }; // 创建新对象，修改属性名
                    })
                    delete formData.Time;
                    delete formData.status;
                    const paramsObject = formData
                    formData.blext1 = blsysuserid.value.value
                    // formData.blext2 = proId.value
                    formData.blsysuserid = blsysuserid.value.value
                    paramsObject["blclosurerecordVo"] = newArr
                    await ProManageApi.UpdateComplete(paramsObject);
                    message.success(`修改成功`);
                    let obj = {
                        type: 0,
                    };
                    emits('emitPass', obj)
                } catch (error) {
                    smartSentry.captureError(error);
                } finally {
                    SmartLoading.hide();
                }
            })
            .catch((error) => {
                message.error('参数验证错误，请仔细填写表单数据!');
            });
    }
    // 所有项目名称  
    const ProList = ref([]);
    async function getAllProjectList() {
        try {
            let departList = await ProManageApi.getApplyFinish();
            const dataSource = departList.data
            ProList.value = departList.data
            options.value = dataSource.map(item => ({
                // value: item.blprojectnum,
                value: item.blext2,
                label: item.blext2
            }));
        } catch (e) {
            smartSentry.captureError(e);
        } finally {

        }
    }
    // 新增待填项  AddlistData
    const peoplePay = ref([])//人员支出
    const publicPay = ref([])//公用支出
    const buildPay = ref([])//基建支出
    const otherPay = ref([])//其他资本性支出
    async function getAddData() {
        try {
            let departList = await ProManageApi.AddlistData();
            const data = departList.data
            // 添加新的属性
            data.forEach(item => {
                item.children.forEach(child => {
                    child.blmoney = '';
                    child.bldollar = '';
                    child.blremarks = '';
                    delete child.children;
                });
            });
            const ruzc = data.find(item => item.bldatanum === 'RYZC').children
            peoplePay.value = JSON.parse(JSON.stringify(ruzc));
            Object.assign(peoplePay, ruzc);
            publicPay.value = data.find(item => item.bldatanum === 'GYZC').children
            buildPay.value = data.find(item => item.bldatanum === 'JJZC').children
            otherPay.value = data.find(item => item.bldatanum === 'QTZBXZC').children
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
        }
    }
    //单条信息  getInfo
    const updateProId = ref(null);
    const dataFormat = 'YYYY-MM-DD'
    async function getViewInfo() {
        SmartLoading.show();
        try {
            const paramsId = props.passData.blclosureid
            let departList = await ProManageApi.getComInfo(paramsId);
            const dataSource = departList.data
            Object.assign(formData, dataSource);
            formData.status = formData.blstate
            if (formData.blstate = 5) {
                formData.blstate = ''
            }
            console.log('formData:', formData)
            formData.Time = [
                dayjs(dataSource.blprojectdatestart, dataFormat),
                dayjs(dataSource.blprojectdateend, dataFormat),
            ]
            updateProId.value = formData.blprojectnum
            console.log('updateProId.value:', updateProId.value)
            // 4 其它资本性支出 QTZBXZC 3基建支出 JJZC 2公用支出 GYZC 1人员支出 RYZC
            const blclosurerecordVo = formData.blclosurerecordVo
            const group1 = []
            const group2 = []
            const group3 = []
            const group4 = []
            console.log('blclosurerecordVo:', blclosurerecordVo)
            blclosurerecordVo.forEach(item => {
                if (item.blbudgetname.startsWith('1')) {
                    group1.push(item);
                } else if (item.blbudgetname.startsWith('2')) {
                    group2.push(item);
                } else if (item.blbudgetname.startsWith('3')) {
                    group3.push(item);
                } else if (item.blbudgetname.startsWith('4')) {
                    group4.push(item);
                }
            });
            const newArr1 = peoplePay.value.map(item1 => {
                const item2 = group1.find(item2 => item2.blbudgetname === item1.bldatanum);
                if (item2) {
                    return { ...item1, ...item2 };
                } else {
                    return item1;
                }
            });
            const newArr2 = publicPay.value.map(item1 => {
                const item2 = group2.find(item2 => item2.blbudgetname === item1.bldatanum);
                if (item2) {
                    return { ...item1, ...item2 };
                } else {
                    return item1;
                }
            });
            const newArr3 = buildPay.value.map(item1 => {
                const item2 = group3.find(item2 => item2.blbudgetname === item1.bldatanum);
                if (item2) {
                    return { ...item1, ...item2 };
                } else {
                    return item1;
                }
            });
            const newArr4 = otherPay.value.map(item1 => {
                const item2 = group4.find(item2 => item2.blbudgetname === item1.bldatanum);
                if (item2) {
                    return { ...item1, ...item2 };
                } else {
                    return item1;
                }
            });
            peoplePay.value = newArr1
            publicPay.value = newArr2
            buildPay.value = newArr3
            otherPay.value = newArr4
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }
    onMounted(() => {
        getAllProjectList()
        getAddData()
        ajaxQueryContact()
        ajaxQuery()
        getViewInfo()
    })
</script>

<style lang="less" scoped>
    .steps-content {
        width: 100%;
        border: 1px dashed #e9e9e9;
        border-radius: 6px;
        min-height: 510px;
        padding-top: 40px;
        margin: 20px auto;
    }

    ::v-deep .ant-table-thead {
        background-color: #fff;
    }

    .steps-action {
        margin-top: 24px;
        float: right;
    }
</style>